<template>
  <div class="app-container">
    <el-form
      ref="ruleForm"
      :inline="true"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-card class="box-card">
        <div
          slot="header"
          class="clearfix"
        >
          <span>项目简介</span>
        </div>
        <div>
          <el-form-item
            label="名称："
            prop="projectName"
          >
            <el-input
              v-model="ruleForm.projectName"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="logo图："
            prop="projectIcon"
          >
            <el-upload
              v-model="ruleForm.projectIcon"
              class="upload-demo"
              :action="imagesUploadApi"
              :limit="1"
              :headers="headers"
              :on-change="handleChange"
              :file-list="imgList"
            >
              <el-button
                size="small"
                type="text"
              >上传</el-button>
            </el-upload>
            <img v-if="this.$route.query.projectId" style="width: 200px; height: 200px;" :src="ruleForm.projectIcon" alt="">
          </el-form-item>
          <el-form-item
            label="最高收益："
            prop="maxEarnings"
          >
            <el-input
              v-model.number="ruleForm.maxEarnings"
              type="number"
              placeholder="请输入"
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="利益点："
            prop="benefitPoint"
          >
            <el-input
              v-model="ruleForm.benefitPoint"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="项目类型："
            prop="projectType"
          >
            <el-select
              v-model="ruleForm.projectType"
              placeholder="请选择"
            >
              <el-option
                label="推文"
                value="推文"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="!this.$route.query.projectId"
            label="书单："
            prop="bookListLink"
          >
            <el-button type="text" size="small" @click="openDialog">上传</el-button>
          </el-form-item>
          <el-form-item
            label="书单链接："
            prop="bookListLink"
          >
            <el-input
              v-model="ruleForm.bookListLink"
              placeholder="请输入"
            />
          </el-form-item>
        </div>
      </el-card>
      <el-card style="margin-top: 20px;">
        <div
          slot="header"
          class="clearfix"
        >
          <span>结算方式</span>
        </div>
        <el-table
          ref="tabledatas"
          :data="ruleForm.settlementMethodList"
          size="mini"
          border
          height="360"
          @selection-change="selectionChange"
        >
          <el-table-column
            type="selection"
            width="80"
          />
          <el-table-column
            label="结算方式"
            prop="settlementName"
          />
          <el-table-column
            label="结算价格"
            prop="personalIncome"
          >
            <template slot-scope="scope">
              <el-form-item :prop="'settlementMethodList.' + scope.$index + '.personalIncome'" :rules="chooseIndex.includes(scope.$index) ? rules.personalIncome : {}">
                <el-input
                  v-model.number="scope.row.personalIncome"
                  type="number"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="平台收益">
            <template slot-scope="scope">
              <el-form-item :prop="'settlementMethodList.' + scope.$index + '.platformIncome'">
                <el-input
                  v-model.number="scope.row.platformIncome"
                  onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
                />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card style="margin-top: 20px;">
        <div
          slot="header"
          class="clearfix"
        >
          <span>项目说明</span>
        </div>
        <el-form-item prop="requirements">
          <div ref="editor" />
        </el-form-item>
      </el-card>
      <el-card style="margin-top: 20px;">
        <div
          slot="header"
          class="clearfix"
        >
          <span>教程说明</span>
        </div>
        <div ref="teditor" />
      </el-card>
      <el-form-item style="margin-top: 10px">
        <el-button
          v-if="!this.$route.query.projectId"
          type="primary"
          @click="submitForm('ruleForm')"
        >确定</el-button>
        <el-button
          v-if="this.$route.query.projectId"
          type="primary"
          @click="editForm('ruleForm')"
        >确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialog" title="上传书单" :close-on-click-modal="false" append-to-body width="500px">
      <el-upload
        :on-success="handleBSuccess"
        :limit="1"
        :file-list="fileList"
        :headers="headers"
        :action="baseApi+'/api/book/importToList'"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="info" @click="crud.doExport">下载模板</el-button>
        <el-button type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addProject, getProjects, editTutorial, editProject } from '@/api/project'
import { mapGetters } from 'vuex'
import crudBook from '@/api/book'
import CRUD, { presenter, header, crud } from '@crud/crud'
import { upload } from '@/utils/upload'
import { getToken } from '@/utils/auth'
import E from 'wangeditor'
var editor = null
var teditor = null
export default {
  name: 'AddProject',
  cruds() {
    return CRUD({ title: '书单', url: 'api/book', crudMethod: { ...crudBook }})
  },
  mixins: [presenter(), header(), crud()],
  data() {
    return {
      ruleForm: {
        projectName: '',
        projectType: '',
        projectIcon: '',
        tutorial: {
          tutorialContent: ''
        },
        bookListLink: '',
        requirements: '',
        maxEarnings: null,
        benefitPoint: '',
        settlementMethodList: [{
          id: 0,
          settlementName: '拉新量',
          platformIncome: '',
          personalIncome: ''
        },
        {
          id: 1,
          settlementName: '按会员量',
          platformIncome: '',
          personalIncome: ''
        },
        {
          id: 2,
          settlementName: '按拉旧量',
          platformIncome: '',
          personalIncome: ''
        },
        {
          id: 3,
          settlementName: '日常',
          platformIncome: '',
          personalIncome: ''
        },
        {
          id: 4,
          settlementName: '按会员充值佣金',
          platformIncome: '',
          personalIncome: ''
        }]
      },
      imgList: [],
      bookList: [],
      sList: ['拉新量', '按会员量', '按拉旧量', '日常', '按会员充值佣金'],
      title: '文件', dialog: false, fileList: [], files: [],
      checkList: ['关键词'],
      headers: {
        'Authorization': getToken()
      },
      chooseIndex: [],
      settlementMethodList: [],
      rules: {
        projectName: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        projectIcon: [
          { required: true, message: '请上传', trigger: 'blur' }
        ],
        projectType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        benefitPoint: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        requirements: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        personalIncome: [{
          required: true,
          message: '请输入',
          type: 'number',
          tirgger: 'blur'
        }],
        maxEarnings: [{
          required: true,
          type: 'number',
          message: '请输入',
          tirgger: 'blur'
        }],
        bookListLink: {
          required: true,
          message: '请输入',
          tirgger: 'blur'
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi'
    ])
  },
  created() {
    if (this.$route.query.projectId) {
      getProjects({
        projectId: this.$route.query.projectId
      }).then((res) => {
        const s = res.content[0].settlementMethodList
        s.forEach((item, index) => {
          if (this.sList.includes(item.settlementName)) {
            this.$refs.tabledatas.toggleRowSelection(
              this.ruleForm.settlementMethodList[this.sList.indexOf(item.settlementName)],
              true
            )
            this.ruleForm.settlementMethodList[this.sList.indexOf(item.settlementName)].settlementName = item.settlementName
            this.ruleForm.settlementMethodList[this.sList.indexOf(item.settlementName)].platformIncome = item.platformIncome
            this.ruleForm.settlementMethodList[this.sList.indexOf(item.settlementName)].personalIncome = item.personalIncome
          }
        })
        delete res.content[0].settlementMethodList
        this.ruleForm = { ...this.ruleForm, ...res.content[0] }
        console.log(this.ruleForm)
        this.createData()
      })
    } else {
      this.createData()
    }
  },
  methods: {
    inEditor() {
      const _this = this
      editor = new E(this.$refs.editor)
      // 自定义菜单配置
      editor.config.zIndex = 10
      // 文件上传
      editor.config.customUploadImg = function(files, insert) {
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法
        files.forEach(image => {
          upload(_this.imagesUploadApi, image).then(res => {
            const data = res.data
            const url = _this.baseApi + '/file/' + data.type + '/' + data.realName
            insert(url)
          })
        })
      }
      editor.config.onchange = (html) => {
        this.ruleForm.requirements = html
      }
      editor.create()
    },
    intEditor() {
      const _this = this
      teditor = new E(this.$refs.teditor)
      // 自定义菜单配置
      teditor.config.zIndex = 10
      // 文件上传
      teditor.config.customUploadImg = function(files, insert) {
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法
        files.forEach(image => {
          upload(_this.imagesUploadApi, image).then(res => {
            const data = res.data
            const url = _this.baseApi + '/file/' + data.type + '/' + data.realName
            insert(url)
          })
        })
      }
      teditor.config.onchange = (html) => {
        if (this.ruleForm.tutorial) { this.ruleForm.tutorial.tutorialContent = html }
      }
      teditor.create()
    },
    createData() { // 新建或者编辑回显
      this.$nextTick(() => { // 使用 this.$nextTick 获取焦点
        this.inEditor() // 调用上面写的方法
        this.intEditor()
        editor.txt.html(this.ruleForm.requirements) // 向富文本中插入回显的数据
        teditor.txt.html(this.ruleForm.tutorial ? this.ruleForm.tutorial.tutorialContent : '') // 向富文本中插入回显的数据
      })
    },
    handleBSuccess(response) {
      this.bookList = response
    },
    doSubmit() {
      this.fileList = []
      this.dialog = false
    },
    openDialog() {
      this.bookList = []
      this.dialog = true
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.settlementMethodList.length === 0) {
            this.$message.warning('请填写结算方式')
          } else {
            this.settlementMethodList.forEach((item) => {
              delete item.id
            })
            this.bookList.forEach((item) => {
              delete item.projectId
            })
            addProject({ ...this.ruleForm, settlementMethodList: this.settlementMethodList, bookList: this.bookList }).then((res) => {
              this.$message.success('添加成功！')
              this.$router.go(-1)
            })
          }
        } else {
          this.$message.success('添加有误！')
          return false
        }
      })
    },
    editForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.settlementMethodList.length === 0) {
            this.$message.warning('请填写结算方式')
          } else {
            this.settlementMethodList.forEach((item) => {
              delete item.id
            })
            this.bookList.forEach((item) => {
              delete item.projectId
            })
            editTutorial({
              tutorialId: this.ruleForm.tutorial.tutorialId,
              projectId: this.$route.query.projectId,
              tutorialContent: this.ruleForm.tutorial.tutorialContent
            })
            editProject({ ...this.ruleForm, settlementMethodList: this.settlementMethodList, bookList: this.bookList }).then((res) => {
              this.$message.success('修改成功！')
              this.$router.go(-1)
            })
          }
        } else {
          this.$message.success('添加有误！')
          return false
        }
      })
    },
    selectionChange(selection) {
      this.settlementMethodList = selection
      if (selection.length > 0) {
        this.chooseIndex = []
        selection.forEach((item) => {
          this.chooseIndex.push(item.id)
        })
      } else {
        this.chooseIndex = []
      }
    },
    handleChange(file, fileList) {
      this.imgList = fileList.slice(-3)
      if (this.imgList[0].response) {
        this.ruleForm.projectIcon = this.baseApi + '/file/' + this.imgList[0].response.type + '/' + this.imgList[0].response.realName
      }
    },
    cancel() {
      this.$refs.ruleForm.resetFields()
      this.$router.go(-1)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
  height: calc(100vh - 50px);
  overflow: auto;
}
::v-deep(.el-button--text) {
  border: 0;
  padding: 0;
  width: 60px;
  background-color: #fff;
  color: #1890ff;
}
.edit {
  z-index: 9999;
  position: relative;
}
</style>
